﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using Oracle.DataAccess.Types;
using Oracle.DataAccess.Client;

namespace Logistics.DataManage.OracleDb
{
    public class ParameterizedOraSQL
    {
        public String SQL { get; set; }
        public IDataParameter[] Parameters { get; set; }

        public ParameterizedOraSQL()
        { 
        }

        public ParameterizedOraSQL(String _SQL, params IDataParameter[] _Parameters)
        { 
            this.SQL = _SQL;
            this.Parameters = _Parameters;
        }


        /// <summary>
        /// 适配SQL中的匿名参数
        /// </summary>
        /// <param name="SQL">包含匿名参数的SQL语句</param>
        /// <param name="param">参数对象列表</param>
        /// <returns></returns>
        public static ParameterizedOraSQL AdaptSQLAnonymousParams(string SQL, params object[] param)
        {
            System.Data.IDataParameter[] IParams;
            IParams = null;
            if (!String.IsNullOrEmpty(SQL) && param != null && param.Length > 0)
            {
                ParameterizedOraSQL ps = new ParameterizedOraSQL();
                if (SQL.EndsWith("?"))
                    SQL += " ";//这里添加一个空格，避免Split后，数组个数错误
                String[] parts = SQL.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length - 1 != param.Length)
                    throw new ArgumentException("SQL中匿名参数个数与参数列表不匹配");

                StringBuilder sBuilder = new StringBuilder(parts[0]);
                ArrayList arr = new ArrayList();
                for (int i = 1; i < parts.Length; i++)
                {
                    string paraName = ":p" + i;
                    sBuilder.Append(paraName + parts[i]);
                    arr.Add(new OracleParameter(paraName, param[i - 1]));
                }
                IParams = (IDataParameter[])arr.ToArray(typeof(IDataParameter));
                ps.SQL = sBuilder.ToString();
                ps.Parameters = IParams;
                return ps;
            }
            //没有加工
            ParameterizedOraSQL defaultps = new ParameterizedOraSQL();
            defaultps.SQL = SQL;
            return defaultps;
        }
    }
}
